<!-- 沿用旧设备 -->
<template>
  <div v-loading="loading" class="investment-analysis">
    <!-- <el-button @click="getList">quoteId:{{ props.quoteId }}</el-button> -->
    <div style="display: flex; justify-content: space-between; gap: 16px">
      <div style="width: 300px; height: 300px" id="chart2" class="hidden-chart"></div>
      <!-- <div class="wave">
          <button class="button">
            <span class="liquid" ref="liquid"></span>
            <span class="btn-txt"></span>
          </button>
        </div> -->
      <div style="width: 300px; height: 300px" id="chart3" class="hidden-chart"></div>
    </div>
    <br />
    <div style="display: flex; justify-content: space-between; gap: 16px">
      <div style="width: 300px; height: 300px" id="chart4" class="hidden-chart"></div>
      <div style="width: 300px; height: 300px" id="chart5" class="hidden-chart"></div>
    </div>
    <div style="display: flex; gap: 20px">
      <div
        v-for="(img, index) in base64Image"
        :key="index"
        style="flex: 1"
        @click="insertImage(img)"
        @dragstart.prevent
      >
        <img :src="img" alt="" style="width: 100%; cursor: pointer" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, shallowRef, onBeforeUnmount, computed, nextTick, onMounted, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import fetch from '@/api/fetch'
import * as echarts from 'echarts'
import message from '@/utils/message'
import useCreateElement from '@/hooks/useCreateElement'
const { createImageElement } = useCreateElement()

const props = defineProps<{
  quoteId: string;
}>()

const { t } = useI18n()

const loading = ref(false)
const data = ref({
  quotePrice: 0,
  eqptTotalPrice: 0,
  funcTotalPrice: 0,
  travelTotalPrice: 0,
  ebTotal: 0,
  totalPrice: 0,
  historyEbTotal: 0,
  historyTotalPrice: 0,
  eqptProp: 0,
  multiple: 0,
})

const chart2 = shallowRef<echarts.ECharts | null>(null)
const chart3 = shallowRef<echarts.ECharts | null>(null)
const chart4 = shallowRef<echarts.ECharts | null>(null)
const chart5 = shallowRef<echarts.ECharts | null>(null)

const initValueLine = computed(() => data.value.historyTotalPrice - data.value.totalPrice)
const base64Image = reactive({
  img1: '',
  img2: '',
  img3: '',
  img4: '',
})

const getList = async () => {
  try {
    loading.value = true
    if (!props.quoteId) throw new Error('quoteId is required')
    const response = await fetch.get(`/system/investment/statisticsFunc?quoteId=${props.quoteId}`)
    const { code, data: responseData } = response as any
    if (code === 601) {
      message.warning(t('investment.tip_import'))
      return
    }

    data.value = responseData
    await nextTick()
    initCharts()
    handleResizeCustom()
    const { img1, img2, img3, img4 } = generateBase64Image()
    base64Image.img1 = img1
    base64Image.img2 = img2
    base64Image.img3 = img3
    base64Image.img4 = img4
  }
  finally {
    loading.value = false
  }
}

const initCharts = () => {
  chart2.value = echarts.init(document.getElementById('chart2') as HTMLElement, null, {
    devicePixelRatio: window.devicePixelRatio,
  })
  chart3.value = echarts.init(document.getElementById('chart3') as HTMLElement, null, {
    devicePixelRatio: window.devicePixelRatio,
  })
  chart4.value = echarts.init(document.getElementById('chart4') as HTMLElement, null, {
    devicePixelRatio: window.devicePixelRatio,
  })
  chart5.value = echarts.init(document.getElementById('chart5') as HTMLElement, null, {
    devicePixelRatio: window.devicePixelRatio,
  })

  const analysis = genEnergyOptions([
    {
      data: [data.value.ebTotal, data.value.totalPrice],
      type: 'bar',
      name: t('investment.system.new_system'),
      label: {
        show: true,
        position: 'top',
        formatter: '{c}',
      },
    },
    {
      data: [data.value.historyEbTotal, data.value.historyTotalPrice],
      type: 'bar',
      name: t('investment.system.historical_energy_consumption'),
      label: {
        show: true,
        position: 'top',
        formatter: '{c}',
      },
    },
  ])
  const eneryProp = genPropOptions()
  const compareBar = genCompareBarOptions()
  const compareLine = genCompareLineOptions()

  chart2.value.setOption(analysis)
  chart3.value.setOption(eneryProp)
  chart4.value.setOption(compareBar)
  chart5.value.setOption(compareLine)
}

const handleResize = () => {
  if (chart2.value) chart2.value.resize()
  if (chart3.value) chart3.value.resize()
  if (chart4.value) chart4.value.resize()
  if (chart5.value) chart5.value.resize()
}

const handleResizeCustom = () => {
  const width = 979
  const height = 383

  if (chart2.value) chart2.value.resize({ width, height })
  if (chart3.value) chart3.value.resize({ width, height })
  if (chart4.value) chart4.value.resize({ width, height })
  if (chart5.value) chart5.value.resize({ width, height })
}


const genEnergyOptions = (data: any) => {
  return {
    title: [
      {
        text: t('investment.system.energy_analysis'),
        left: 'left',
        top: 'top',
      },
      {
        text: t('investment.power_unit'),
        left: 'left',
        top: '30px',
        textStyle: {
          fontSize: 12,
          fontWeight: 'normal',
        },
      },
      {
        text: t('investment.electricity_unit'),
        right: '10%',
        top: '30px',
        textStyle: {
          fontSize: 12,
          fontWeight: 'normal',
        },
      },
    ],
    xAxis: {
      type: 'category',
      data: [t('investment.power_consumption'), t('investment.electricity_cost')],
    },
    yAxis: {
      type: 'value',
    },
    legend: {
      bottom: '0%',
      itemGap: 50, // 设置图例项之间的间隔
    },
    series: data,

    grid: {
      containLabel: true,
      left: '5%',
      right: '5%',
      bottom: '8%',
    },
  }
}

const genPropOptions = () => {
  return {
    title: {
      text: t('investment.system.ratio'),
      right: 'left',
    },
    series: [
      {
        type: 'pie',
        radius: ['60%', '63%'],
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'normal',
          position: 'center',
          formatter: t('investment.system.ratio') + '\n\n' + '{c}%',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'normal',
          },
        },
        labelLine: {
          show: false,
        },
        data: [{ value: data.value.eqptProp, name: 'eqptProp', itemStyle: { color: '#5e91f9' } }],
      },
    ],
    grid: {
      containLabel: true,
      left: '5%',
      right: '5%',
      bottom: '5%',
    },
  }
}

const genCompareBarOptions = () => {
  return {
    title: [
      {
        text: t('investment.unit'),
        right: 'right',
        textStyle: {
          fontSize: 12,
          fontWeight: 'normal',
        },
      },
      {
        text: t('investment.system.comparison'),
        left: 'left',
        top: 'top',
      },
    ],
    xAxis: {
      type: 'category',
      data: Array.from({ length: Math.min(data.value.multiple, 12) }, (_, i) => t(`investment.year_${Number(i) + 1}`)),
    },
    yAxis: {
      type: 'value',
    },
    legend: {
      top: '10%',
      itemGap: 50,
    },
    series: [
      {
        data: Array.from({ length: Math.min(data.value.multiple, 12) }, (_, i) =>
          (data.value.totalPrice * (i + 1)).toFixed(2)
        ),
        type: 'bar',
        name: t('investment.system.new_system'),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
      },
      {
        data: Array.from({ length: Math.min(data.value.multiple, 12) }, (_, i) =>
          (data.value.historyTotalPrice * (i + 1)).toFixed(2)
        ),
        type: 'bar',
        name: t('investment.system.historical_energy_consumption'),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
      },
    ],
    grid: {
      containLabel: true,
      left: '5%',
      right: '5%',
      bottom: '5%',
    },
  }
}

const genCompareLineOptions = () => {
  return {
    title: [
      {
        text: t('investment.unit'),
        right: 'right',
        textStyle: {
          fontSize: 12,
          fontWeight: 'normal',
        },
      },
      {
        text: t('investment.system.expected_payback_period'),
        left: 'left',
        top: 'top',
      },
    ],
    xAxis: {
      type: 'category',
      data: Array.from({ length: Math.min(data.value.multiple, 12) }, (_, i) => t(`investment.year_${Number(i) + 1}`)),
    },
    yAxis: {
      type: 'value',
    },
    legend: {
      top: '10%',
      itemGap: 0,
    },
    series: [
      {
        data: Array.from({ length: Math.min(data.value.multiple, 12) }, (_, i) =>
          (initValueLine.value * (i + 1)).toFixed(2)
        ),
        type: 'line',
        itemStyle: { color: '#d9001b' },
        name: t('investment.system.cost'),
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
        },
      },
      {
        data: Array.from({ length: 12 }, (_, i) => (data.value.quotePrice * (i + 1)).toFixed(2)),
        type: 'line',
        itemStyle: { color: '#f7b157' },
        name: t('investment.system.project_investment_cost'),
      },
    ],
    grid: {
      containLabel: true,
      left: '5%',
      right: '5%',
      bottom: '5%',
    },
  }
}

const generateBase64Image = () => {
  const img1 = chart5.value?.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
  })
  const img2 = chart4.value?.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
  })
  const img3 = chart2.value?.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
  })
  const img4 = chart3.value?.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff',
  })

  return {
    img1,
    img2,
    img3,
    img4,
  }
}

// const dragStart = (e: DragEvent) => {
//   console.log(e.target.src, 'e.target.src')
//   e.dataTransfer.setData('text/plain', (e.target as HTMLImageElement).src)
// }

// const handleDragEnd = (e: DragEvent) => {
//   e.preventDefault()
//   console.log('拖动结束')
// }

const insertImage = (url) => {
  createImageElement(url, {
    left: 0,
    top: 100
  })
}

onMounted(async () => {
  await nextTick()
  window.addEventListener('resize', handleResizeCustom)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResizeCustom)
})

defineExpose({
  getList,
  generateBase64Image,
})
</script>

<style scoped lang="scss">
.hidden-chart {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

.investment-analysis {
  overflow-y: auto;
  height: 300px;
}
.flex {
  display: flex;
  align-items: center;
}

.chart-box {
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-radius: 3px;
  padding: 12px 12px 24px;
  margin: 12px 0;
  overflow: auto;
}

/* From Uiverse.io by abuayaan01 */
.wave {
  position: absolute;
  left: 50%;
  top: 51%;
  transform: translate(-50%, -50%);
}
.button {
  background-color: transparent;
  /* border: 0px; */
  /* outline: 0px; */
  /* color: #fff; */
  width: 200px;
  height: 200px;
  padding: 20px;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
}

.liquid {
  background-color: rgba(40, 147, 235, 0.8);
  width: 250px;
  // 水位高度调整height，50-310
  height: 5px;
  position: absolute;
  bottom: 0;
  left: 0;
  // box-shadow: inset 5px -5px 25px #104e81, inset -5px 0px 25px #104e81;
}

.liquid::after {
  content: '';
  width: 450px;
  height: 430px;
  background: #ffffff;
  z-index: 1;
  position: absolute;
  left: -110px;
  top: -380px;
  border-radius: 45%;
  animation: animate 5s linear 2s infinite;
}

.liquid::before {
  content: '';
  width: 450px;
  height: 430px;
  background-color: rgb(68, 160, 235);
  z-index: 1;
  position: absolute;
  left: -110px;
  top: -380px;
  border-radius: 40%;
  animation: animate 5s linear 1.8s infinite;
}

.btn-txt {
  position: relative;
  z-index: 1;
  font-size: 22px;
  font-family: sans-serif;
  letter-spacing: 2px;
}

@keyframes animate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
